#!/usr/bin/env python

import subprocess, sys, os, tempfile, shlex

def main(args):
    # format for P4MERGE is: p4merge base theirs yours merge
    if len(args) != 5:
        print >>sys.stderr, 'usage: %s <base> <theirs> <yours> <merge>'
        sys.exit(-1)

    base, theirs, yours, output = args[1:]

    # attempt the merge
    merge = subprocess.Popen(['merge', '-p', yours, base, theirs],
                             stdout = subprocess.PIPE)
    out = merge.communicate()[0]
    if merge.returncode != 0:
        editor = shlex.split(os.environ.get('P4EDITOR', 'nano'))
        # this would be so much easier with the with statement
        # with statement wasn't added until 2.6 (2.5 with __future__ module)
        try:
            fd, tmp = tempfile.mkstemp()
            try: os.write(fd, out)
            finally: os.close(fd)

            timestamp = os.stat(tmp).st_mtime
            editor.append(tmp)
            subprocess.call(editor)
            if os.stat(tmp).st_mtime > timestamp:
                f = open(tmp, 'r')
                try: out = f.read()
                finally: f.close()
            else:
                sys.exit(1)
        finally: os.remove(tmp)

    outfile = open(output, 'w')
    try: outfile.write(out)
    finally: outfile.close()

if __name__ == '__main__':
    main(sys.argv)
